package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.SmsConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private RedisCache redisCache;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String username = user.getUsername();


        if (StringUtils.isEmpty(username))
        {
            return error("用户名不能为空！");
        }

        String code = user.getCode();
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("未填写验证码");
        }
        String redisCode = redisCache.getCacheObject(SmsConstants.VERIFICATION_CODE + SmsConstants.REGIST + username);
        if (!code.equals(redisCode)) {
            return AjaxResult.error("验证码错误");
        }

        if (StringUtils.isNotBlank(user.getPromoter()) && "undefined".equals(user.getPromoter())) {
            logger.error("未能正确获取到推广人信息，请联系客服处理！ 入参信息：{}", JSONObject.toJSONString(user));
            return AjaxResult.error("未能正确获取到推广人信息，请联系客服处理！");
        }

        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }
}
